import time
import hmac
import hashlib
import base64
import urllib.parse

from dingtalkchatbot.chatbot import DingtalkChatbot


class SendText:
    def __init__(self, webhook):
        # 初始化机器人小丁
        self.xiaoding = DingtalkChatbot(webhook)

    def send_text(self, msg):
        # Text消息
        self.xiaoding.send_text(msg=msg, is_at_all=False)

    # 后续可新增@对应项目owner


def autograph(url, secret):
    """
    加密逻辑
    :param url:
    :param secret:
    :return:
    """
    timestamp = str(round(time.time() * 1000))
    secret_enc = secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    end_url = "{}&timestamp={}&sign={}".format(url, timestamp, sign)
    return end_url
